using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Plan;
using WPF_MVVM_Test.MVVM_ViewModel.Plan;

namespace WPF_MVVM_Test.Services.Plan
{
    /// <summary>
    /// 生产计划服务类 - 完全使用后端API数据
    /// </summary>
    public class ProductPlanService : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private const string BASE_URL = "http://8.140.242.140:8888/api/ProductionPlans";

        public ProductPlanService()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
            // 设置默认请求头
            _httpClient.DefaultRequestHeaders.Add("accept", "text/plain");
            
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true,
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                // 允许从字符串读取数字
                NumberHandling = JsonNumberHandling.AllowReadingFromString,
                // 只添加planQuantity需要的转换器
                Converters = 
                {
                    new StringToDecimalConverter()
                }
            };
        }

        /// <summary>
        /// 获取生产计划列表 - 完全使用后端API数据
        /// </summary>
        /// <param name="planNumber">计划编号筛选</param>
        /// <param name="unit">单位筛选</param>
        /// <param name="status">状态筛选</param>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>生产计划列表和分页信息</returns>
        public async Task<(List<ProductplanModel> plans, int totalCount, int totalPage)> GetProductPlansAsync(
            string? planNumber = "",
            string? unit = "",
            int? status = null,
            int pageIndex = 1,
            int pageSize = 10)
        {
            try
            {
                // 构建查询参数
                var queryParams = BuildQueryParameters(planNumber, unit, status, pageIndex, pageSize);
                var requestUrl = $"{BASE_URL}?{queryParams}";

                System.Diagnostics.Debug.WriteLine($"🌐 请求URL: {requestUrl}");

                // 发送HTTP请求
                var response = await _httpClient.GetAsync(requestUrl);

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"📦 API响应: {jsonContent}");

                    var apiResponse = JsonSerializer.Deserialize<ProductPlanApiResponse>(jsonContent, _jsonOptions);

                    if (apiResponse?.IsSuc == true && apiResponse.Data?.Data != null)
                    {
                        // 为每个项目添加序号
                        AssignIndexToPlans(apiResponse.Data.Data, (pageIndex - 1) * pageSize);
                        
                        System.Diagnostics.Debug.WriteLine($"✅ 成功获取 {apiResponse.Data.Data.Count} 条记录，总计 {apiResponse.Data.TotalCount} 条");
                        
                        return (
                            apiResponse.Data.Data,
                            apiResponse.Data.TotalCount,
                            apiResponse.Data.TotalPage
                        );
                    }
                    else
                    {
                        throw new Exception($"API返回错误: {apiResponse?.Msg ?? "未知错误"}");
                    }
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"🚨 获取生产计划列表异常: {ex.Message}");
                throw new Exception($"获取生产计划列表失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 获取生产计划总数和总页数
        /// </summary>
        public async Task<(int totalCount, int totalPage)> GetProductPlanCountAsync(
            string? planNumber = "",
            string? unit = "",
            int? status = null)
        {
            try
            {
                // 构建查询参数（只获取第一条记录来获取总数信息）
                var queryParams = BuildQueryParameters(planNumber, unit, status, 1, 1);
                var requestUrl = $"{BASE_URL}?{queryParams}";

                var response = await _httpClient.GetAsync(requestUrl);

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<ProductPlanApiResponse>(jsonContent, _jsonOptions);

                    if (apiResponse?.IsSuc == true && apiResponse.Data != null)
                    {
                        return (apiResponse.Data.TotalCount, apiResponse.Data.TotalPage);
                    }
                    else
                    {
                        throw new Exception($"API返回错误: {apiResponse?.Msg ?? "未知错误"}");
                    }
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取生产计划总数异常: {ex.Message}");
                throw new Exception($"获取生产计划总数失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 根据ID获取单个生产计划详情
        /// </summary>
        /// <param name="id">计划ID</param>
        /// <returns>生产计划详情</returns>
        public async Task<ProductplanModel?> GetProductPlanByIdAsync(string id)
        {
            try
            {
                var response = await _httpClient.GetAsync($"{BASE_URL}/{id}");

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<SingleProductPlanApiResponse>(jsonContent, _jsonOptions);
                    
                    if (apiResponse?.IsSuc == true && apiResponse.Data != null)
                    {
                        return apiResponse.Data;
                    }
                    else
                    {
                        throw new Exception($"API返回错误: {apiResponse?.Msg ?? "未知错误"}");
                    }
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取生产计划详情异常: {ex.Message}");
                throw new Exception($"获取生产计划详情失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 创建生产计划
        /// </summary>
        /// <param name="productPlan">生产计划数据</param>
        /// <returns>是否创建成功</returns>
        public async Task<bool> CreateProductPlanAsync(AddProductplanModel productPlan)
        {
            try
            {
                var jsonContent = JsonSerializer.Serialize(productPlan, _jsonOptions);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                System.Diagnostics.Debug.WriteLine($"🌐 创建生产计划请求URL: {BASE_URL}");
                System.Diagnostics.Debug.WriteLine($"📦 请求数据: {jsonContent}");

                var response = await _httpClient.PostAsync(BASE_URL, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"✅ 创建成功响应: {responseContent}");

                    var apiResponse = JsonSerializer.Deserialize<BaseApiResponse>(responseContent, _jsonOptions);
                    return apiResponse?.IsSuc == true;
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"❌ 创建失败: {response.StatusCode} - {errorContent}");
                    throw new Exception($"创建生产计划失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"🚨 创建生产计划异常: {ex.Message}");
                throw new Exception($"创建生产计划失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 更新生产计划
        /// </summary>
        /// <param name="productPlan">生产计划数据</param>
        /// <returns>是否更新成功</returns>
        public async Task<bool> UpdateProductPlanAsync(UpdateProductplanModel productPlan)
        {
            try
            {
                var jsonContent = JsonSerializer.Serialize(productPlan, _jsonOptions);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                // 使用PUT请求，URL与后端API保持一致
                var updateUrl = $"{BASE_URL}/UpdateProductionPlan";
                System.Diagnostics.Debug.WriteLine($"🌐 更新生产计划请求URL: {updateUrl}");
                System.Diagnostics.Debug.WriteLine($"📦 请求数据: {jsonContent}");

                // 使用PUT方法替代POST
                var response = await _httpClient.PutAsync(updateUrl, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"✅ 更新成功响应: {responseContent}");

                    var apiResponse = JsonSerializer.Deserialize<BaseApiResponse>(responseContent, _jsonOptions);
                    return apiResponse?.IsSuc == true;
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"❌ 更新失败: {response.StatusCode} - {errorContent}");
                    throw new Exception($"更新生产计划失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"🚨 更新生产计划异常: {ex.Message}");
                throw new Exception($"更新生产计划失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 分解生产计划
        /// </summary>
        /// <param name="planId">生产计划ID</param>
        /// <returns>分解是否成功</returns>
        public async Task<bool> DecomposeProductPlanAsync(Guid planId)
        {
            try
            {
                var decomposeUrl = $"http://8.140.242.140:8888/api/BomDecomposition/decompose/{planId}";
                System.Diagnostics.Debug.WriteLine($"🌐 分解生产计划请求URL: {decomposeUrl}");

                // 使用POST请求进行分解操作
                var response = await _httpClient.PostAsync(decomposeUrl, null);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"✅ 分解成功响应: {responseContent}");

                    var apiResponse = JsonSerializer.Deserialize<BaseApiResponse>(responseContent, _jsonOptions);
                    return apiResponse?.IsSuc == true;
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"❌ 分解失败: {response.StatusCode} - {errorContent}");
                    throw new Exception($"分解生产计划失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"🚨 分解生产计划异常: {ex.Message}");
                throw new Exception($"分解生产计划失败: {ex.Message}", ex);
            }
        }

        #region 私有辅助方法

        /// <summary>
        /// 构建查询参数字符串
        /// </summary>
        private string BuildQueryParameters(string? planNumber, string? unit, int? status, int pageIndex, int pageSize)
        {
            var queryParams = new List<string>();

            // 只有非空值才添加到查询参数中
            if (!string.IsNullOrWhiteSpace(planNumber))
            {
                queryParams.Add($"planNumber={Uri.EscapeDataString(planNumber)}");
                System.Diagnostics.Debug.WriteLine($"🔍 添加计划编号/名称搜索: {planNumber}");
            }
            
            if (!string.IsNullOrWhiteSpace(unit))
            {
                queryParams.Add($"unit={Uri.EscapeDataString(unit)}");
                System.Diagnostics.Debug.WriteLine($"🔍 添加单位搜索: {unit}");
            }
            
            if (status.HasValue)
            {
                queryParams.Add($"status={status.Value}");
                System.Diagnostics.Debug.WriteLine($"🔍 添加状态搜索: {status.Value}");
            }

            // 分页参数（必需）
            queryParams.Add($"pageIndex={pageIndex}");
            queryParams.Add($"pageSize={pageSize}");

            var result = string.Join("&", queryParams);
            System.Diagnostics.Debug.WriteLine($"🌐 完整查询参数: {result}");
            
            return result;
        }

        /// <summary>
        /// 为计划列表分配序号
        /// </summary>
        private void AssignIndexToPlans(List<ProductplanModel> plans, int skipCount)
        {
            for (int i = 0; i < plans.Count; i++)
            {
                plans[i].Index = skipCount + i + 1;
                
                // 调试信息：验证planQuantity的decimal转换
                System.Diagnostics.Debug.WriteLine($"📊 计划 {plans[i].Index}: " +
                    $"编号={plans[i].PlanNumber}, " +
                    $"名称={plans[i].PlanName}, " +
                    $"数量={plans[i].PlanQuantity:F2} (decimal), " +
                    $"状态={plans[i].Status} (int)");
            }
        }

        #endregion

        #region 资源释放

        public void Dispose()
        {
            _httpClient?.Dispose();
        }

        #endregion
    }

    #region API响应模型

    /// <summary>
    /// 基础API响应
    /// </summary>
    public class BaseApiResponse
    {
        [JsonPropertyName("isSuc")]
        public bool IsSuc { get; set; }

        [JsonPropertyName("code")]
        public int Code { get; set; }

        [JsonPropertyName("msg")]
        public string Msg { get; set; } = string.Empty;
    }

    /// <summary>
    /// 单个生产计划API响应
    /// </summary>
    public class SingleProductPlanApiResponse : BaseApiResponse
    {
        [JsonPropertyName("data")]
        public ProductplanModel? Data { get; set; }
    }

    /// <summary>
    /// 产品名称列表API响应
    /// </summary>
    public class ProductNamesApiResponse : BaseApiResponse
    {
        [JsonPropertyName("data")]
        public List<string>? Data { get; set; }
    }

    /// <summary>
    /// 检查存在性API响应
    /// </summary>
    public class CheckExistsApiResponse : BaseApiResponse
    {
        [JsonPropertyName("data")]
        public CheckExistsData? Data { get; set; }
    }

    public class CheckExistsData
    {
        [JsonPropertyName("exists")]
        public bool Exists { get; set; }
    }

    #endregion
}
